package thread_base.thread_safe;

import annotation.NotThreadSafe;

import java.math.BigInteger;

@NotThreadSafe
public class UnsafeCountingFactorizer {

    private long count = 0;

    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = factor(i);
        // 此处操作非原子性操作
        // 其包含三步操作：1.读取count、2.count+1、3.写入count
        count++;
        encodeIntoResponse(resp, factors);
    }

    BigInteger[] factor(BigInteger i) {
        // Doesn't really factor
        return new BigInteger[]{i};
    }

    BigInteger extractFromRequest(ServletRequest req) {
        return new BigInteger("7");
    }

    void encodeIntoResponse(ServletResponse resp, BigInteger[] factors) {
    }

    public long getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        UnsafeCountingFactorizer countingFactorizer = new UnsafeCountingFactorizer();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                countingFactorizer.service(null, null);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                countingFactorizer.service(null, null);
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("count: " + countingFactorizer.getCount());
    }
}
